﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using SufeiUtil_Core;
using WangLong;
using System.IO;
using System.Net;

namespace 封包测试工具
{
    public class FanYi
    {
        #region API配置
        public string appid = "20160708000024853";
        public string appkey = "I4WHin1vQKXSpTnEtjXK";
        #endregion
        public string BaiDuFanYi(string msg)
        {
            string[] strs = msg.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries);
            if (strs.Length > 1)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 1; i < strs.Length; i++)
                {
                    sb.Append(strs[i]);
                    if (i != strs.Length - 1)
                    {
                        sb.Append(" ");
                    }
                }
                return Fanyi(strs[0], sb.ToString());
            }
            else
            {
                return Fanyi(msg);
            }
        }//机器人翻译接口
        private string Fanyi(string content)
        {
            bool chines = IsChines(content);
            return Fanyi(content, "auto", chines?"en":"zh");
        }//翻译不指定语言
        private string Fanyi(string language, string content)
        {
            string[] strs = language.Split(new string[] { "翻译" },StringSplitOptions.RemoveEmptyEntries);
            if (strs.Length<=1)
            {
                 strs = language.Split(new string[] { "译" }, StringSplitOptions.RemoveEmptyEntries);
            }
            if (strs.Length>1)
            {
                string to = GetLanguage(strs[1]);
                if (to!="auto")
                {
                    string from= GetLanguage(strs[0]);
                    return Fanyi(content, from, to);
                }
            }
            return Fanyi(language +" "+ content);
        }//翻译指定语言
        public string Fanyi(string content,string from,string to)
        {
            try
            {
                    //client_id为自己的api_id，q为翻译对象，from为翻译语言，to为翻译后语言
                    string salt = DateTimeToUnixTimestamp(DateTime.Now).ToString();
                    string sign = GetMD5String(appid + content + salt + appkey);
                    //Console.WriteLine(appid + content + salt + appkey);
                 
                HttpHelper http = new HttpHelper();
                HttpItem item = new HttpItem();
                item.URL = "http://api.fanyi.baidu.com/api/trans/vip/translate";
                item.ContentType = "application/x-www-form-urlencoded";
                item.Method = "POST";
                item.Postdata= string.Format("q={0}&from={1}&to={2}&appid={3}&salt={4}&sign={5}", HttpUtility.UrlEncode(content, Encoding.UTF8) , from, to, appid, salt, sign);
                //拼接appid=2015063000000001+q=apple+salt=1435660288+密钥=12345678
                //得到字符串1 =2015063000000001apple143566028812345678
                //>计算签名sign（对字符串1做md5加密，注意计算md5之前，串1必须为UTF-8编码）
                //sign=md5(2015063000000001apple143566028812345678)
                //string url = string.Format("http://openapi.baidu.com/public/2.0/bmt/translate?client_id={0}&q={1}&from={2}&to={3}", "sIMTakCOCFNKvzGbbfIGE0vK", neirong, from, to);
                HttpResult result = http.GetHtml(item);
                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    TranClass tran = JSON.parse<TranClass>(result.Html);
                    StringBuilder sb = new StringBuilder();
                    foreach (var fanyiitem in tran.trans_result)
                    {
                        sb.AppendLine(fanyiitem.dst);
                    }
                    return sb.ToString().TrimEnd();
                }
                else
                {
                    return "啊哦~翻译请求出错，稍后重试！";
                }
                
            }
            catch (Exception ex)
            {

                return "啊哦~翻译出错了，稍后重试吧！\r\n错误提示：" + ex.Message;
            }
        }//实际翻译操作接口
        private string GetLanguage(string Name)
        {

            switch (Name)
            {
                case "中":
                case "中文": return "zh";
                case "英":
                case "英语": return "en";
                case "粤":
                case "粤语": return "yue";
                case "文":
                case "文言文": return "wyw";
                case "日":
                case "日语": return "jp";
                case "韩":
                case "韩语": return "kor";
                case "法":
                case "法语": return "fra";
                case "西":
                case "西班牙语": return "spa";
                case "泰":
                case "泰语": return "th";
                case "阿":
                case "阿拉伯语": return "ara";
                case "俄":
                case "俄语": return "ru";
                case "葡":
                case "葡萄牙语": return "pt";
                case "德":
                case "德语": return "de";
                case "意":
                case "意大利语": return "it";
                case "希":
                case "希腊语": return "el";
                case "荷":
                case "荷兰语": return "nl";
                case "波":
                case "波兰语": return "pl";
                case "保":
                case "保加利亚语": return "bul";
                case "爱":
                case "爱沙尼亚语": return "est";
                case "丹":
                case "丹麦语": return "dan";
                case "芬":
                case "芬兰语": return "fin";
                case "捷":
                case "捷克语": return "cs";
                case "罗":
                case "罗马尼亚语": return "rom";
                case "斯":
                case "斯洛文尼亚语": return "slo";
                case "瑞":
                case "瑞典语": return "swe";
                case "匈":
                case "匈牙利语": return "hu";
                case "繁":
                case "繁体中文": return "cht";
                case "越":
                case "越南语": return "vie";
                default: return "auto";
            }
        }//语言获取
        private bool IsChines(string str)
        {
            Regex reg = new Regex("[\u4e00-\u9fa5]");
            return reg.Match(str).Success;
        }//是否为中文

        #region 百度翻译所需辅助函数
        /// <summary>
        /// 日期转换成unix时间戳
        /// </summary>
        /// <param name="dateTime"></param>
        /// <returns></returns>
        public long DateTimeToUnixTimestamp(DateTime dateTime)
        {
            var start = new DateTime(1970, 1, 1, 0, 0, 0, dateTime.Kind);
            return Convert.ToInt64((dateTime - start).TotalSeconds);
        }
        /// <summary> 
        /// 字符串转换 
        /// </summary> 
        /// <param name="str">要转换的字符串</param> 
        /// <returns></returns> 
        public string GetMD5String(string str)
        {
            MD5 md5 = MD5.Create();
            byte[] b = Encoding.UTF8.GetBytes(str);
            byte[] md5b = md5.ComputeHash(b);
            md5.Clear();
            StringBuilder sb = new StringBuilder();
            foreach (var item in md5b)
            {
                sb.Append(item.ToString("x2"));
            }
            return sb.ToString();
        }
        #endregion

        #region BaiDuFanYiJson
        public class TransResult
        {
            public string src { get; set; }
            public string dst { get; set; }
        }
        public class TranClass
        {
            public string from { get; set; }
            public string to { get; set; }
            public IList<TransResult> trans_result { get; set; }
        }
        #endregion
    }
    public class FanyiYouDao {

        Regex reg=new Regex("errorCode=(.*?)\\s+result=([\\s\\S]+)");
        public string Fanyi(string content)
        {
            try
            {
             
                HttpHelper http = new HttpHelper();
                HttpItem item = new HttpItem();
                item.URL = "http://fanyi.youdao.com/translate";
                item.ContentType = "application/x-www-form-urlencoded";
                item.Method = "POST";
                item.Postdata = string.Format("i={0}&type=auto&doctype=text&xmlVersion=1.1&keyfrom=360se", HttpUtility.UrlEncode(content, Encoding.UTF8));
                HttpResult result = http.GetHtml(item);
                if (result.StatusCode == System.Net.HttpStatusCode.OK)
                {
                    Match match= reg.Match(result.Html);
                    if (match.Success)
                    {
                        if (match.Groups[1].Value=="0")
                        {
                            return match.Groups[2].Value;
                        }
                        return "啊哦~翻译失败,错误原因"+match.Groups[1].Value;
                    }
                    return "啊哦~翻译失败,未匹配到结果";
                }
                else
                {
                    return "啊哦~翻译请求出错，稍后重试！";
                }

            }
            catch (Exception ex)
            {

                return "啊哦~翻译出错了，稍后重试吧！\r\n错误提示：" + ex.Message;
            }
        }//实际翻译操作接口
    }

}
